const axios = require('axios')
const cheerio = require('cheerio')
const iconv = require('iconv-lite')

module.exports = async(ctx, next) => {
    var url = ctx.query.url
        // console.log(url)
    var content = await new Promise((resolve, reject) => {
        axios({
            method: 'get',
            url: 'https://www.81book.com' + url,
            responseType: 'stream'
        }).then(res => {
                var stream = []
                res.data.on('data', st => {
                    stream.push(st)
                })
                res.data.on('end', () => {
                    var buffer = Buffer.concat(stream)
                    let domStr = iconv.decode(buffer, 'utf8')
                    var $ = cheerio.load(domStr)
                        // 这里如果使用text()会失去换行符,
                    var text = $('#content').html()
                    var tit = $('h1').text()
                    resolve({ tit: tit, text: text })
                })
            },
            err => {
                reject(err)
            })
    })
    ctx.body = content
}